package http
import(	
	. "nightowl/config"
    "encoding/json"
    "io/ioutil"
    "fmt"
    "strings"
)
const(
	MODEL_EDGE_CLIENT = "edge-client"

	FUNC_SEARCH = "search"
	FUNC_GET = "get"
	FUNC_REMOVE = "remove"
	FUNC_UPDATE = "update"
	FUNC_REGISTRY = "registry"
)
// type ApiFunc func(PathVars, Params map[string] interface{}, Headers map[string]string)
type ApiFunc func(reqParams RequestParams)
var Api = make (map[string]map[string] ApiFunc) 
func init(){
	data, err := ioutil.ReadFile("resources/api.json")
    if err != nil {
        fmt.Printf("read api.json error:", err)
        return
    }
    var result map[string]interface{}
    if err := json.Unmarshal(data, &result); err != nil {
        fmt.Printf("Unmarshal api.json error:", err)
        return
    }
    for k, v := range result{
    	if _, exists := Api[k]; !exists{
    		Api[k] = make (map[string] ApiFunc)
    	}
    	m, ok := v.(map[string]interface{})
    	if !ok{
    		continue
    	}
    	for methodName, conf := range m{
    		methodConf, ok := conf.(map[string]interface{})
    		if !ok{
	    		continue
	    	}
    		Api[k][methodName] = func(reqParams RequestParams){
				host := ENV_CONFIG.CentralConfig.Server
    			url := host + methodConf["url"].(string)
    			method := methodConf["method"].(string)
    			headers := make(map[string]string)
    			if methodConf["headers"] != nil{
    				if m, ok := methodConf["headers"].(map[interface{}]interface{}); ok {
        				for k, v := range m {
        					headers[k.(string)] = v.(string)
        				}
        			}
    			}


    			if reqParams.PathVars != nil{
    				for k, v := range reqParams.PathVars{
    					url = strings.Replace(url, "{"+k+"}", v.(string), -1)
    				}
    			}
    			if reqParams.Headers != nil{
    				for k, v := range reqParams.Headers{
    					headers[k] = v
    				}
    			}
    			if method != "GET" {
    				if _, ok := headers["content-type"]; !ok {
    					headers["content-type"] = "application/json"
    				}
    			}

        		// fmt.Printf("request|%s %s|prams:%s\n", method, url, Params)
    			requestParams := RequestParams{
					Url: url,
					Method: method, 
					Params: reqParams.Params,
					Headers: headers,
				}

				Request(requestParams)
    		}
    	}
    }
}
func ApiRequest(module, action string, reqParams RequestParams){
	Api[module][action](reqParams)
}